// 文件路径: frontend/static/js/intervention_record.js

// 干预操作记录模块前端JS（配置驱动版，与视力模块保持一致）

document.addEventListener("DOMContentLoaded", function () {
  // 初始化
  let selectedStudent = null;
  window.selectedStudent = null;
  let currentRecords = [];
  let editingRecordId = null;
  let lastSavedRecordId = null; // 记录最后保存的记录ID，用于导出功能
  // ✅新增：配置驱动支持
  let interventionConfig = null;
  let queryFieldsConfig = null;
  let historyFieldsConfig = null;
  let globalFieldConfig = null;

  // ✅新增：加载干预配置（全局唯一配置驱动）
  async function loadInterventionConfig() {
    try {
      console.log("🔧 开始加载干预配置...");
      
      // 1. 获取全局字段配置
      const globalFieldResp = await fetch("/api/config/all_field_config");
      if (globalFieldResp.ok) {
        const globalFieldData = await globalFieldResp.json();
        if (globalFieldData.success) {
          globalFieldConfig = globalFieldData.config;
          console.log("✅ 全局字段配置加载成功:", globalFieldConfig);
        }
      } else {
        console.warn("⚠️ 全局字段配置接口不存在");
      }
      
      // 2. 获取查询字段配置
      const queryFieldsResp = await fetch("/api/config/query-fields");
      if (queryFieldsResp.ok) {
        const queryFieldsData = await queryFieldsResp.json();
        if (queryFieldsData.success) {
          queryFieldsConfig = queryFieldsData.fields;
          console.log("✅ 查询字段配置加载成功:", queryFieldsConfig);
          renderQueryArea();
        }
      } else {
        console.warn("⚠️ 查询字段配置接口不存在，使用干预配置");
      }
      
      // 3. 获取历史记录字段配置
      const historyFieldsResp = await fetch("/api/config/history_fields/intervention");
      if (historyFieldsResp.ok) {
        const historyFieldsData = await historyFieldsResp.json();
        if (historyFieldsData.success) {
          historyFieldsConfig = historyFieldsData.fields;
          console.log("✅ 历史记录字段配置加载成功:", historyFieldsConfig);
        }
      } else {
        console.warn("⚠️ 历史记录字段配置接口不存在");
      }
      
      // 4. 获取完整干预配置
      const response = await fetch("/api/config/intervention/records");
      const data = await response.json();
      if (data.success) {
        interventionConfig = data.config;
        console.log("✅ 干预配置加载成功:", interventionConfig);
        console.log("🔧 查询结果字段配置:", interventionConfig.search_result_fields);
        
        // 如果查询字段配置未加载成功，使用干预配置中的查询字段
        if (!queryFieldsConfig && interventionConfig.query_fields) {
          queryFieldsConfig = interventionConfig.query_fields;
          console.log("✅ 使用干预配置中的查询字段:", queryFieldsConfig);
          renderQueryArea();
        }
        
        initializeFormWithConfig();
      } else {
        console.error("❌ 干预配置加载失败:", data.message);
      }
    } catch (error) {
      console.error("❌ 配置加载异常:", error);
    }
  }

  // ✅新增：使用FixedQueryArea渲染查询区
  function renderQueryArea() {
    if (!queryFieldsConfig) {
      console.warn("⚠️ 查询配置未加载，跳过查询区渲染");
      return;
    }
    
    console.log("🔧 开始渲染配置驱动查询区:", queryFieldsConfig);
    
    if (window.renderFixedQueryArea) {
      window.renderFixedQueryArea(
        queryFieldsConfig,
        "fixedQueryArea",
        onSearch,
        onClear,
        false // 禁用列配置按钮
      );
    } else {
      console.error("❌ FixedQueryArea.js 未正确加载");
    }
  }

  // ✅恢复：原有的学生查询逻辑（保持模块独立性）
  function onSearch(params) {
    // 添加分页参数
    const searchParams = new URLSearchParams(params);
    const page = params.page || '1';
    searchParams.set('page', page);
    searchParams.set('per_page', '10');
    
    // 指定查询字段为干预模块需要的字段
    const requiredColumns = [
      'id', 'education_id', 'school', 'name', 'gender', 'age', 'phone', 'parent_name', 'parent_phone'
    ];
    searchParams.set('columns', requiredColumns.join(','));
    
    // 执行查询
    const url = `/api/students/query?${searchParams.toString()}`;
    
    fetch(url)
      .then((response) => response.json())
      .then((data) => {
        if (data.success) {
          console.log(`✅ 查询成功，共 ${data.total} 条记录，当前第 ${data.page} 页`);
          
          // 显示查询结果区域
          document.getElementById("search-results").style.display = "block";
          
          // 使用统一的QueryResultTable组件渲染学生表格
          renderStudentTableWithComponent(data.students || []);
          
          // 渲染分页
          renderPagination(data.total, data.page, data.per_page);
        } else {
          console.error("❌ 查询失败:", data.message);
          if (window.Swal) {
            Swal.fire("查询失败", data.message, "error");
          } else {
            alert("查询失败: " + data.message);
          }
        }
      })
      .catch((err) => {
        console.error("查询失败:", err);
        if (window.Swal) {
          Swal.fire("查询失败", err.message, "error");
        } else {
          alert("查询失败: " + err.message);
        }
      });
  }

  // ✅新增：清除按钮回调
  function onClear() {
    console.log("🔧 清除查询条件");
    document.getElementById("search-results").style.display = "none";
    document.getElementById("student-info-bar").classList.remove("show");
  }

  // ✅新增：获取当前查询参数
  function getCurrentQueryParams() {
    const params = {};
    const queryInputs = document.querySelectorAll('#fixedQueryArea input, #fixedQueryArea select');
    queryInputs.forEach(input => {
      if (input.value && input.name) {
        params[input.name] = input.value;
      }
    });
    return params;
  }

  // ✅使用QueryResultTable组件渲染学生表格（与视力模块完全一致）
  async function renderStudentTableWithComponent(students) {
    if (!window.renderQueryResultTable) {
      console.error("❌ QueryResultTable组件未加载");
      return;
    }

    try {
      // 使用新的自包含QueryResultTable API
      await window.renderQueryResultTable(students, 'intervention', 'query', {
        showRowNumber: true,
        onRowClick: (row, index) => {
          // 点击学生行事件
        }
      });
    } catch (error) {
      console.error('❌ 干预模块表格渲染失败:', error);
      
      // 降级处理：显示错误信息
      const tableBody = document.getElementById('queryTableBody');
      if (tableBody) {
        tableBody.innerHTML = `
          <tr>
            <td colspan="100%" class="text-center text-danger py-4">
              <i class="fas fa-exclamation-triangle fa-2x mb-2 d-block"></i>
              <div>表格渲染失败: ${error.message}</div>
            </td>
          </tr>
        `;
      }
    }
  }

  // ✅新增：初始化表单配置
  function initializeFormWithConfig() {
    // 如果配置已加载，初始化表单
    if (interventionConfig) {
      console.log("🔧 使用配置初始化表单");
      // 初始化级联下拉框等
      initializeCascadingSelects();
      // 初始化所有下拉框选项
      updateSelectOptions();
      // 初始化干预类型下拉框
      initializeInterventionTypeSelect();
    }
  }

  // 页面初始化时加载配置
  loadInterventionConfig();

  // 页面初始化时强制隐藏学生信息条
  document.getElementById("student-info-bar").classList.remove("show");

  // ✅新增：干预模块专用操作按钮处理函数（供QueryResultTable组件调用）
  function showStudentHistory(studentId) {
    console.log("显示干预历史，学生ID:", studentId);
    loadStudentBaseInfo(studentId, function(student) {
      if (student) {
        selectedStudent = student;
        console.log("✅ 学生信息加载成功，准备显示历史记录");
        showHistoryTable(studentId);
      } else {
        console.error("❌ 学生信息加载失败");
      }
    });
  }

  function selectStudent(studentId) {
    console.log("选择学生录入，学生ID:", studentId);
    loadStudentBaseInfo(studentId, function(student) {
      if (student) {
        selectedStudent = student;
        console.log("✅ 学生信息加载成功，准备显示录入表单");
        showInterventionForm();
              } else {
        console.error("❌ 学生信息加载失败");
              }
    });
        }
        
  // ✅新增：全局函数声明（供QueryResultTable组件调用）
  window.showStudentHistory = showStudentHistory;
  window.selectStudent = selectStudent;
      


  // ✅ 字段显示名映射函数 - 从全局配置获取
  function getFieldDisplayName(fieldName) {
    // 1. 优先从查询字段配置获取显示名称
    if (queryFieldsConfig && Array.isArray(queryFieldsConfig)) {
      const fieldConfig = queryFieldsConfig.find(f => f.field === fieldName);
      if (fieldConfig && fieldConfig.display_name) {
        return fieldConfig.display_name;
      }
    }
    
    // 2. 从全局字段配置获取显示名称
    if (globalFieldConfig) {
      // 检查 student 表字段
      if (globalFieldConfig.student && globalFieldConfig.student[fieldName]) {
        return globalFieldConfig.student[fieldName].display_name;
      }
      
      // 检查 student_extension 表字段
      if (globalFieldConfig.student_extension && globalFieldConfig.student_extension[fieldName]) {
        return globalFieldConfig.student_extension[fieldName].display_name;
      }
      
      // 检查其他表字段
      for (const tableName in globalFieldConfig) {
        if (globalFieldConfig[tableName] && globalFieldConfig[tableName][fieldName]) {
          return globalFieldConfig[tableName][fieldName].display_name;
        }
      }
    }
    
    // 3. 如果都没有找到，返回字段名
    return fieldName;
  }

  // ✅ 渲染历史记录表头 - 配置驱动版本
  function renderHistoryTableHeader() {
    const headerRow = document.getElementById("history-table-header");
    if (!headerRow) return;

    console.log("🔧 开始渲染历史记录表头...");
    console.log("📋 干预配置:", interventionConfig);
    console.log("📋 历史字段配置:", interventionConfig?.history_fields);

    // 使用配置驱动的表头
    if (interventionConfig && interventionConfig.history_fields) {
      headerRow.innerHTML = "";
      
      // 确保history_fields是数组格式
      let fieldsToRender = [];
      if (Array.isArray(interventionConfig.history_fields)) {
        fieldsToRender = interventionConfig.history_fields;
      } else if (typeof interventionConfig.history_fields === 'object') {
        // 如果是对象格式，转换为数组并按order排序
        fieldsToRender = Object.entries(interventionConfig.history_fields)
          .sort(([, a], [, b]) => (a.order || 999) - (b.order || 999))
          .map(([fieldName, config]) => ({ field: fieldName, ...config }));
      }
        
      console.log("📋 准备渲染的字段:", fieldsToRender);
      
      fieldsToRender.forEach(fieldConfig => {
          const th = document.createElement("th");
        
        // 获取显示名称
        let displayName = fieldConfig.display_name;
        if (!displayName && fieldConfig.field) {
          if (fieldConfig.field === 'actions') {
            displayName = "操作";
          } else {
            displayName = getFieldDisplayName(fieldConfig.field);
          }
        }
        
        th.textContent = displayName || fieldConfig.field || "未知";
        console.log(`  添加表头: ${fieldConfig.field} -> ${displayName}`);
        
          if (fieldConfig.width) {
            th.style.width = fieldConfig.width;
          }
          headerRow.appendChild(th);
        });
    } else {
      // 默认表头
      console.log("⚠️ 使用默认表头配置");
      const defaultHeaders = ["干预日期", "操作时间", "干预方式", "操作医生", "操作地点", "配合程度", "即时效果", "操作"];
      headerRow.innerHTML = "";
      defaultHeaders.forEach(header => {
        const th = document.createElement("th");
        th.textContent = header;
        headerRow.appendChild(th);
      });
    }
    
    console.log("✅ 历史记录表头渲染完成，列数:", headerRow.children.length);
  }



  function renderPagination(total, page, per_page) {
    const pageCount = Math.ceil(total / per_page);
    if (pageCount <= 1) {
      document.getElementById("pagination-bar").innerHTML = "";
      return;
    }
    let html = "";
    html += `<button class="page-btn" ${
      page === 1 ? "disabled" : ""
    } data-page="${page - 1}">上一页</button>`;
    let start = Math.max(1, page - 2);
    let end = Math.min(pageCount, page + 2);
    if (start > 1) html += "<span>...</span>";
    for (let i = start; i <= end; i++) {
      html += `<button class="page-btn${
        i === page ? " active" : ""
      }" data-page="${i}">${i}</button>`;
    }
    if (end < pageCount) html += "<span>...</span>";
    html += `<button class="page-btn" ${
      page === pageCount ? "disabled" : ""
    } data-page="${page + 1}">下一页</button>`;
    document.getElementById("pagination-bar").innerHTML = html;

    // 事件绑定
    document.querySelectorAll(".page-btn").forEach((btn) => {
      btn.addEventListener("click", function () {
        const toPage = parseInt(this.getAttribute("data-page"));
        if (!isNaN(toPage) && toPage !== page) {
          // 重新执行查询，传递当前查询参数和页码
          const currentParams = getCurrentQueryParams();
          currentParams.page = toPage;
          onSearch(currentParams);
        }
      });
    });
  }

  // 加载学生基本信息
  function loadStudentBaseInfo(studentId, callback) {
    console.log("调用 loadStudentBaseInfo，studentId:", studentId);
    fetch(`/api/students/get?student_id=${studentId}`)
      .then((res) => res.json())
      .then((data) => {
        console.log("loadStudentBaseInfo 返回数据:", data);
        if (!data.student) {
          if (window.Swal) {
            Swal.fire("获取学生信息失败", "", "error");
          } else {
            alert("获取学生信息失败");
          }
          return;
        }
        selectedStudent = data.student;
        window.selectedStudent = selectedStudent; // 保证全局可用
        fillStudentInfoBar(selectedStudent);
        document.getElementById("student-info-bar").classList.add("show");
        callback && callback(selectedStudent);
      });
  }

  // 填充学生基本信息横条 - 使用全局统一组件
  async function fillStudentInfoBar(stu) {
    console.log("填充学生信息条:", stu);
    try {
      // 使用全局统一的学生信息栏组件
      await renderStudentInfoBar(stu, {
        moduleName: 'intervention',
        containerId: 'student-info-bar',
        autoShow: true,
        onError: (error) => {
          console.error('❌ 学生信息条组件渲染失败:', error);
        }
      });
    } catch (error) {
      console.error('❌ 学生信息条组件调用失败:', error);
    }
  }

  // 显示干预录入表单（支持只读和编辑模式）
  function showInterventionForm(record = null, readonly = false) {
    document.getElementById("search-results").style.display = "none";
    document.getElementById("pagination-bar").style.display = "none";
    document.getElementById("intervention-form").reset();
    document.getElementById("intervention-form").style.display = "block";
    document.getElementById("history-table-area").style.display = "none";

    // 确保配置已加载
    if (!interventionConfig) {
      console.warn("配置未加载，等待配置加载完成");
      setTimeout(() => showInterventionForm(record, readonly), 500);
      return;
    }

    // 重新初始化级联下拉框（因为reset()会清空容器内容）
    console.log("🔄 showInterventionForm: 准备重新初始化级联下拉框");
    initializeCascadingSelects();
    
    // 初始化所有下拉框选项
    updateSelectOptions();
    initializeInterventionTypeSelect();

    // 自动填充当前日期、时间、默认干预方式（仅新建时）
    if (!record) {
      const now = new Date();
      // 日期
      const today = now.toISOString().split("T")[0];
      const dateInput = document.querySelector(
        '#intervention-form [name="intervention_date"]'
      );
      if (dateInput) dateInput.value = today;
      // 时间
      const currentTime = now.toTimeString().substring(0, 5);
      const timeInput = document.querySelector(
        '#intervention-form [name="operation_time"]'
      );
      if (timeInput) timeInput.value = currentTime;
      // 默认干预方式
      const interventionSelect = document.querySelector(
        '#intervention-form [name="intervention_type"]'
      );
      if (interventionSelect && interventionConfig.intervention_types) {
        const defaultType = "耳穴压丸";
        if (interventionConfig.intervention_types.includes(defaultType)) {
          interventionSelect.value = defaultType;
          renderSpecificFields(defaultType);
        }
      }
    }

    // 填充表单（包括24个新增字段）
    if (record) {
      fillFormWithRecord(record);
    }
    // 只读模式
    Array.from(
      document.querySelectorAll(
        "#intervention-form input, #intervention-form select, #intervention-form textarea"
      )
    ).forEach((el) => {
      el.disabled = !!readonly;
    });
    if (record && record.id) {
      editingRecordId = record.id;
      lastSavedRecordId = record.id; // 设置lastSavedRecordId以支持直接导出
    } else {
      editingRecordId = null;
      lastSavedRecordId = null;
    }
    // 编辑按钮
    let editBtn = document.getElementById("btn-edit-record");
    if (readonly && !editBtn) {
      editBtn = document.createElement("button");
      editBtn.id = "btn-edit-record";
      editBtn.type = "button";
      editBtn.className = "btn btn-warning ms-2";
      editBtn.textContent = "编辑";
      editBtn.onclick = () => showInterventionForm(record, false);
      document
        .querySelector("#intervention-form .mb-3.text-end")
        .appendChild(editBtn);
    } else if (!readonly && editBtn) {
      editBtn.remove();
    }
  }

  // 配置驱动：统一填充表单记录（完全修复版本）
  function fillFormWithRecord(record) {
    console.log("fillFormWithRecord调用，记录数据:", record);

    // 第一步：渲染字段结构
    if (record.intervention_type) {
      renderSpecificFields(record.intervention_type);
      updateCascadingOptions(record.intervention_type);
    }

    // 第二步：等待DOM更新完成后填充数据
    setTimeout(() => {
      // 填充基础字段
      fillBasicFields(record);

      // 填充级联下拉框数据
      fillCascadingFieldsData(record);

      // 填充专用字段数据
      fillSpecificFieldsData(record);

      console.log("所有字段数据填充完成");
    }, 150);
  }

  // 新增：填充基础字段
  function fillBasicFields(record) {
    const basicFields = [
      "intervention_date",
      "operation_time",
      "intervention_type",
      "operator",
      "duration_minutes",
      "operation_location",
      "immediate_effect",
      "cooperation_level",
      "patient_reaction",
      "details",
    ];

    basicFields.forEach((key) => {
      const el = document.querySelector(`#intervention-form [name="${key}"]`);
      if (el && record[key] !== null && record[key] !== undefined) {
        if (key === "intervention_date" && record.intervention_date) {
          el.value = record.intervention_date.split("T")[0];
        } else if (key === "operation_time" && record.operation_time) {
          el.value =
            record.operation_time.length > 5
              ? record.operation_time.slice(0, 5)
              : record.operation_time;
        } else if (el.type === "number") {
          el.value = record[key];
        } else {
          el.value = record[key];
        }
      }
    });
  }

  // 新增：填充级联下拉框数据
  function fillCascadingFieldsData(record) {
    console.log("🔄 开始填充级联下拉框数据，记录:", record);

    // 🔍 调试：显示三个字段的原始数据
    console.log("🔍 三个字段的原始数据:");
    console.log(
      "   - operation_tools 原始值:",
      record.operation_tools,
      "类型:",
      typeof record.operation_tools
    );
    console.log(
      "   - consumed_materials 原始值:",
      record.consumed_materials,
      "类型:",
      typeof record.consumed_materials
    );
    console.log(
      "   - operation_sites 原始值:",
      record.operation_sites,
      "类型:",
      typeof record.operation_sites
    );

    const cascadingFields = [
      "operation_tools",
      "consumed_materials",
      "operation_sites",
    ];

    cascadingFields.forEach((fieldName) => {
      if (record[fieldName]) {
        const fieldData = safeParseArray(record[fieldName]);
        console.log(`📝 处理字段 ${fieldName}，数据:`, fieldData);

        if (fieldData.length > 0) {
          // 更新隐藏字段
          const hiddenInput = document.getElementById(`${fieldName}-hidden`);
          if (hiddenInput) {
            hiddenInput.value = JSON.stringify(fieldData);
            console.log(`✅ 更新隐藏字段 ${fieldName}:`, hiddenInput.value);
          }

          // 等待DOM更新后再选中复选框和更新显示
          setTimeout(() => {
            // 选中对应的复选框
            let checkedCount = 0;
            fieldData.forEach((value) => {
              const checkbox = document.querySelector(
                `input[id^="${fieldName}_"][value="${value}"]`
              );
              if (checkbox) {
                checkbox.checked = true;
                checkedCount++;
                console.log(`✅ 选中复选框: ${fieldName} - ${value}`);
              } else {
                console.warn(`❌ 未找到复选框: ${fieldName} - ${value}`);
              }
            });

            // 更新显示状态
            const button = document.getElementById(`${fieldName}-dropdown`);
            const selectedContainer = document.getElementById(
              `${fieldName}-selected`
            );
            const tagsContainer = document.getElementById(`${fieldName}-tags`);

            if (button) {
              button.textContent = `已选${fieldData.length}项`;
              console.log(
                `✅ 更新按钮文字: ${fieldName} - 已选${fieldData.length}项`
              );
            }
            if (selectedContainer) {
              selectedContainer.style.display = "block";
            }
            if (tagsContainer) {
              tagsContainer.innerHTML = fieldData
                .map(
                  (value) =>
                    `<span class="badge bg-primary me-1">${value}</span>`
                )
                .join("");
              console.log(
                `✅ 更新标签显示: ${fieldName}`,
                tagsContainer.innerHTML
              );
            }
          }, 200); // 延迟200ms确保下拉菜单内容已生成
        }
      } else {
        console.log(`⚠️ 字段 ${fieldName} 无数据或为假值:`, record[fieldName]);
      }
    });
  }

  // 新增：填充专用字段数据
  function fillSpecificFieldsData(record) {
    if (!interventionConfig || !record.intervention_type) return;

    const typeConfig =
      interventionConfig.intervention_config_map[record.intervention_type];
    if (!typeConfig || !typeConfig.specific_fields) return;

    // 填充专用字段的复选框
    Object.keys(typeConfig.specific_fields).forEach((fieldName) => {
      const fieldConfig = typeConfig.specific_fields[fieldName];

      if (fieldConfig.field_type === "multi_checkbox" && record[fieldName]) {
        const fieldData = safeParseArray(record[fieldName]);
        document
          .querySelectorAll(`#intervention-form [name="${fieldName}"]`)
          .forEach((cb) => {
            cb.checked = fieldData.includes(cb.value);
          });
      } else if (
        record[fieldName] !== null &&
        record[fieldName] !== undefined
      ) {
        const el = document.querySelector(
          `#intervention-form [name="${fieldName}"]`
        );
        if (el) {
          if (el.type === "number") {
            el.value = record[fieldName];
          } else if (el.type !== "checkbox") {
            el.value = record[fieldName];
          }
        }
      }
    });
  }

  // 绑定保存
  document
    .getElementById("intervention-form")
    .addEventListener("submit", function (e) {
      e.preventDefault();
      if (!selectedStudent) {
        if (window.Swal) {
          Swal.fire("请先选择学生", "", "info");
        } else {
          alert("请先选择学生");
        }
        return;
      }

      const formData = new FormData(this);

      // 基础字段
      const payload = {
        student_id: selectedStudent.id,
        intervention_date: formData.get("intervention_date"),
        operation_time: formData.get("operation_time"),
        intervention_type: formData.get("intervention_type"),
        operator: formData.get("operator"),
        duration_minutes: formData.get("duration_minutes")
          ? Number(formData.get("duration_minutes"))
          : null,
        operation_location: formData.get("operation_location"),
        immediate_effect: formData.get("immediate_effect"),
        cooperation_level: formData.get("cooperation_level"),
        patient_reaction: formData.get("patient_reaction"),
        details: formData.get("details"),
        // ✅ 修复：添加序号字段，让后端计算
        session_number: null,  // 后端会根据历史记录计算
        global_sequence: null, // 后端会根据历史记录计算
      };

      // 配置驱动：级联下拉框字段处理
      const cascadingFields = [
        "operation_tools",
        "consumed_materials",
        "operation_sites",
      ];
      cascadingFields.forEach((fieldName) => {
        const hiddenInput = document.getElementById(`${fieldName}-hidden`);
        if (hiddenInput && hiddenInput.value) {
          try {
            const fieldData = JSON.parse(hiddenInput.value);
            if (Array.isArray(fieldData) && fieldData.length > 0) {
              payload[fieldName] = fieldData;
            }
          } catch (e) {
            console.warn(`解析级联字段 ${fieldName} 数据失败:`, e);
          }
        }
      });

      // 配置驱动：专用字段处理
      if (interventionConfig && payload.intervention_type) {
        const typeConfig =
          interventionConfig.intervention_config_map[payload.intervention_type];
        if (typeConfig && typeConfig.specific_fields) {
          Object.keys(typeConfig.specific_fields).forEach((fieldName) => {
            const fieldConfig = typeConfig.specific_fields[fieldName];

            if (fieldConfig.field_type === "multi_checkbox") {
              // 复选框字段
              const checkedValues = Array.from(
                document.querySelectorAll(`input[name="${fieldName}"]:checked`)
              ).map((el) => el.value);
              if (checkedValues.length > 0) {
                payload[fieldName] = checkedValues;
              }
            } else if (fieldConfig.field_type === "number") {
              // 数字字段
              const value = formData.get(fieldName);
              if (value) {
                payload[fieldName] = Number(value);
              }
            } else {
              // 普通字段
              const value = formData.get(fieldName);
              if (value) {
                payload[fieldName] = value;
              }
            }
          });
        }
      }

      let url, method;
      if (editingRecordId) {
        url = `/api/intervention_records/${editingRecordId}`;
        method = "PUT";
      } else {
        url = "/api/intervention_records";
        method = "POST";
      }
      fetch(url, {
        method: method,
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(payload),
      })
        .then((res) => res.json())
        .then((data) => {
          if (data.success) {
            lastSavedRecordId = data.data.id;
            editingRecordId = null;
            if (window.Swal) {
              Swal.fire({
                icon: "success",
                title: "保存成功",
                text: "干预记录已保存！",
                confirmButtonText: "确定",
              }).then(() => {
                document.getElementById("intervention-form").reset();
                document.getElementById("intervention-form").style.display =
                  "none";
                showHistoryTable(selectedStudent.id);
              });
            } else {
              alert("保存成功！");
              document.getElementById("intervention-form").reset();
              document.getElementById("intervention-form").style.display =
                "none";
              showHistoryTable(selectedStudent.id);
            }
          } else {
            if (window.Swal) {
              Swal.fire({
                icon: "error",
                title: "保存失败",
                text: data.error || "未知错误",
              });
            } else {
              alert("保存失败：" + (data.error || "未知错误"));
            }
          }
        });
    });

  // 显示历史表格
  function showHistoryTable(studentId) {
    console.log("🔍 调用 showHistoryTable，studentId:", studentId);
    console.log("🔍 selectedStudent:", selectedStudent);
    // 隐藏其它区域
    document.getElementById("search-results").style.display = "none";
    document.getElementById("pagination-bar").style.display = "none";
    document.getElementById("intervention-form").style.display = "none";
    
    // 显示历史表区域（强制显示）
    const area = document.getElementById("history-table-area");
    console.log("🔍 历史表格区域元素:", area);
    if (area) {
    area.classList.add("show");
    area.style.display = "block";
      console.log("✅ 历史表格区域已显示");
    } else {
      console.error("❌ 找不到历史表格区域元素");
    }
    // 加载干预记录
    console.log("🔍 开始加载干预记录，API:", `/api/intervention_records/list?student_id=${studentId}`);
    fetch(`/api/intervention_records/list?student_id=${studentId}`)
      .then((res) => res.json())
      .then((data) => {
        console.log("🔍 干预历史接口返回:", data);
        if (data.success) {
          currentRecords = data.data || [];
          console.log(
            "渲染历史表，记录数:",
            currentRecords.length,
            currentRecords
          );
          
          // 🔧 修复：确保配置加载完成后再渲染表格
          if (interventionConfig && interventionConfig.history_fields) {
            console.log("✅ 配置已加载，直接渲染表格");
          renderHistoryTable(currentRecords);
          } else {
            console.log("⏳ 配置未加载，等待配置加载完成...");
            // 等待配置加载完成
            const checkConfig = () => {
              if (interventionConfig && interventionConfig.history_fields) {
                console.log("✅ 配置加载完成，开始渲染表格");
                renderHistoryTable(currentRecords);
              } else {
                setTimeout(checkConfig, 100);
              }
            };
            checkConfig();
          }
          // ====== 自动调试代码，输出容器显示状态和高度 ======
          (function debugHistoryTableArea() {
            const area = document.getElementById("history-table-area");
            const scrollable = document.getElementById("scrollable-content");
            const row = area?.closest(".row");
            const table = document.getElementById("history-table");
            const tbody = table?.querySelector("tbody");
            console.log("==== 干预历史表格调试信息 ====");
            console.log(
              "#history-table-area display:",
              getComputedStyle(area).display,
              "offsetHeight:",
              area.offsetHeight,
              "clientHeight:",
              area.clientHeight
            );
            console.log(
              "#scrollable-content display:",
              getComputedStyle(scrollable).display,
              "offsetHeight:",
              scrollable.offsetHeight,
              "clientHeight:",
              scrollable.clientHeight
            );
            if (row) {
              console.log(
                ".row display:",
                getComputedStyle(row).display,
                "offsetHeight:",
                row.offsetHeight,
                "clientHeight:",
                row.clientHeight
              );
            }
            if (tbody) {
              console.log("#history-table tbody 行数:", tbody.children.length);
            }
            console.log("============================");
          })();
          // ====== END ======
        } else {
          console.log("接口未返回success，data:", data);
        }
      });
  }

  // 渲染历史表，支持删除
  function renderHistoryTable(records) {
    console.log("进入 renderHistoryTable，records:", records);

    // 🔧 确保表头已渲染
    renderHistoryTableHeader();

    const tbody = document.querySelector("#history-table tbody");
    tbody.innerHTML = "";
    
    if (!records || records.length === 0) {
      tbody.innerHTML = '<tr><td colspan="100%" class="text-center text-muted">暂无历史记录</td></tr>';
      return;
    }
    
    // 获取字段配置用于数据渲染
    let fieldsToRender = [];
    if (interventionConfig && interventionConfig.history_fields) {
      if (Array.isArray(interventionConfig.history_fields)) {
        fieldsToRender = interventionConfig.history_fields;
      } else if (typeof interventionConfig.history_fields === 'object') {
        fieldsToRender = Object.entries(interventionConfig.history_fields)
          .sort(([, a], [, b]) => (a.order || 999) - (b.order || 999))
          .map(([fieldName, config]) => ({ field: fieldName, ...config }));
      }
    }
    
    // 🔧 修复：如果配置为空，使用默认字段配置
    if (fieldsToRender.length === 0) {
      console.log("⚠️ 配置为空，使用默认字段配置");
      fieldsToRender = [
        { field: 'intervention_date', display_name: '干预日期' },
        { field: 'operation_time', display_name: '操作时间' },
        { field: 'intervention_type', display_name: '干预方式' },
        { field: 'operator_name', display_name: '操作医生' },
        { field: 'operation_location', display_name: '操作地点' },
        { field: 'cooperation_level', display_name: '配合程度' },
        { field: 'immediate_effect', display_name: '即时效果' },
        { field: 'actions', display_name: '操作' }
      ];
    }
    
    console.log("📋 用于数据渲染的字段配置:", fieldsToRender);
    
    records.forEach((r, index) => {
      const row = document.createElement("tr");
      
      // 根据配置的字段顺序渲染数据
      fieldsToRender.forEach(fieldConfig => {
        const td = document.createElement("td");
        const fieldName = fieldConfig.field;
        
        if (fieldName === 'actions') {
          // 操作列
          td.innerHTML = `
            <button class="btn btn-link btn-sm btn-show-detail" data-id="${r.id}">详情</button>
            <button class="btn btn-danger btn-sm btn-delete-record" data-id="${r.id}">删除</button>
            <button class="btn btn-secondary btn-sm btn-log-record" data-id="${r.id}">日志</button>
          `;
        } else {
          // 数据列
          let value = r[fieldName] || "";
          
          // 特殊字段格式化
          if (fieldName === 'intervention_date' && value) {
            value = value.split("T")[0]; // 只显示日期部分
          } else if (fieldName === 'operation_time' && value) {
            value = value.slice(0, 5); // 只显示时间部分
          }
          
          td.textContent = value;
        }
        
        row.appendChild(td);
      });
      
      tbody.appendChild(row);
    });
    
    console.log("历史表渲染完成，tbody行数:", tbody.children.length);
    document.querySelectorAll(".btn-show-detail").forEach((btn) => {
      btn.addEventListener("click", function () {
        fetch(`/api/intervention_records/${btn.dataset.id}`)
          .then((res) => res.json())
          .then((data) => {
            if (data.success) showInterventionForm(data.data, true); // 只读详情
          });
      });
    });
    document.querySelectorAll(".btn-delete-record").forEach((btn) => {
      btn.addEventListener("click", function () {
        if (window.Swal) {
          Swal.fire({
            title: "确定要删除该干预记录吗？",
            icon: "warning",
            showCancelButton: true,
            confirmButtonText: "确定",
            cancelButtonText: "取消",
          }).then((result) => {
            if (result.isConfirmed) {
              fetch(`/api/intervention_records/${btn.dataset.id}`, {
                method: "DELETE",
              })
                .then((res) => res.json())
                .then((data) => {
                  if (data.success) {
                    Swal.fire("删除成功", "", "success");
                    showHistoryTable(selectedStudent.id);
                  } else {
                    Swal.fire("删除失败", data.error || "未知错误", "error");
                  }
                });
            }
          });
        } else {
          if (!confirm("确定要删除该干预记录吗？")) return;
          fetch(`/api/intervention_records/${btn.dataset.id}`, {
            method: "DELETE",
          })
            .then((res) => res.json())
            .then((data) => {
              if (data.success) {
                alert("删除成功");
                showHistoryTable(selectedStudent.id);
              } else {
                alert("删除失败：" + (data.error || "未知错误"));
              }
            });
        }
      });
    });
    document.querySelectorAll(".btn-log-record").forEach((btn) => {
      btn.addEventListener("click", function () {
        const recordId = btn.dataset.id;
        // 查询日志并弹窗展示
        fetch(`/api/intervention_records/logs?record_id=${recordId}`)
          .then((res) => res.json())
          .then((data) => {
            if (data.success && data.data.length > 0) {
              let html = data.data
                .map((log) => {
                  let localTime = log.created_at
                    ? new Date(log.created_at).toLocaleString()
                    : "";
                  let restoreButton = "";

                  // 根据日志类型显示不同的恢复按钮
                  const actionLower = log.action.toLowerCase();
                  if (actionLower === "delete") {
                    restoreButton = `<button class="btn btn-sm btn-outline-success mt-2" onclick="restoreDeletedRecord(${log.id})">恢复已删除记录</button>`;
                  } else if (actionLower === "restore") {
                    restoreButton = `<span class="badge bg-info mt-2">恢复操作记录</span>`;
                  } else if (
                    log.old_content &&
                    (actionLower === "create" || actionLower === "update")
                  ) {
                    restoreButton = `<button class="btn btn-sm btn-outline-primary mt-2" onclick="restoreLog(${log.id})">恢复此版本</button>`;
                  }

                  return `<div style="border-bottom:1px solid #eee;margin-bottom:12px;padding-bottom:8px;">
                <div><strong>记录ID：</strong>${
                  log.record_id
                } | <strong>操作类型：</strong>${
                    log.action
                  } | <strong>操作人：</strong>${
                    log.operator || ""
                  } | <strong>时间：</strong>${localTime}</div>
                ${
                  log.new_content
                    ? `<div><strong>当前内容：</strong><pre style="white-space:pre-wrap;font-size:12px;max-height:120px;overflow-y:auto;background:#e8f5e8;padding:8px;border-radius:4px;border-left:4px solid #28a745;">${log.new_content}</pre></div>`
                    : ""
                }
                ${
                  log.old_content
                    ? `<div><strong>历史内容：</strong><pre style="white-space:pre-wrap;font-size:12px;max-height:120px;overflow-y:auto;background:#fff3cd;padding:8px;border-radius:4px;border-left:4px solid #ffc107;">${
                        log.old_content
                      }</pre>${
                        restoreButton
                          ? `<div style="margin-top:8px;">${restoreButton}</div>`
                          : ""
                      }</div>`
                    : ""
                }
                </div>`;
                })
                .join("");

              if (window.Swal) {
                Swal.fire({
                  title: `${
                    selectedStudent.name || "该学生"
                  }的干预记录日志`,
                  html: `<div style="max-height:600px;overflow-y:auto;text-align:left;">${html}</div>`,
                  width: 1000,
                  showConfirmButton: false,
                  showCloseButton: true,
                });
              } else {
                alert("日志功能需要引入 SweetAlert2 支持美观弹窗。");
              }
            } else {
              if (window.Swal) {
                Swal.fire("无日志", "该记录暂无历史日志", "info");
              } else {
                alert("暂无日志");
              }
            }
          })
          .catch((err) => {
            if (window.Swal) {
              Swal.fire("获取日志失败", "网络错误：" + err.message, "error");
            } else {
              alert("获取日志失败：" + err.message);
            }
          });
      });
    });
  }

  // 导出按钮事件绑定（支持多个同名按钮）
  function bindExportButtons() {
    // 先解绑，防止重复绑定
    document
      .querySelectorAll("#btn-export-xlsx, #btn-export-csv")
      .forEach((btn) => {
        btn.onclick = null;
      });

    document.querySelectorAll("#btn-export-xlsx").forEach((btn) => {
      btn.addEventListener("click", function () {
        console.log("🔍 导出Excel按钮被点击");
        const formVisible =
          document.getElementById("intervention-form").style.display !== "none";
        const areaVisible =
          document.getElementById("history-table-area").style.display !==
          "none";
        
        console.log("📋 导出状态检查:");
        console.log("- formVisible:", formVisible);
        console.log("- areaVisible:", areaVisible);
        console.log("- lastSavedRecordId:", lastSavedRecordId);
        console.log("- selectedStudent:", selectedStudent);
        console.log("- 按钮所在容器:", btn.closest("#intervention-form") ? "表单区域" : "历史区域");
        
        if (formVisible && btn.closest("#intervention-form")) {
          console.log("🔧 执行单条记录导出");
          if (!lastSavedRecordId) {
            if (window.Swal) {
              Swal.fire("请先保存一条干预记录后再导出！", "", "info");
            } else {
              alert("请先保存一条干预记录后再导出！");
            }
            return;
          }
          // 修正：csv导出也要用 export_one 路径
          const exportUrl = `/api/intervention_records/export_one?record_id=${lastSavedRecordId}&type=xlsx`;
          console.log("🔗 单条导出URL:", exportUrl);
          window.open(exportUrl);
        } else if (
          areaVisible &&
          btn.closest("#history-table-area") &&
          selectedStudent
        ) {
          console.log("🔧 执行多条记录导出");
          const exportUrl = `/api/intervention_records/export?student_id=${selectedStudent.id}&type=xlsx`;
          console.log("🔗 多条导出URL:", exportUrl);
          window.open(exportUrl);
        } else {
          console.log("❌ 导出条件不满足");
        }
      });
    });

    document.querySelectorAll("#btn-export-csv").forEach((btn) => {
      btn.addEventListener("click", function () {
        const formVisible =
          document.getElementById("intervention-form").style.display !== "none";
        const areaVisible =
          document.getElementById("history-table-area").style.display !==
          "none";
        if (formVisible && btn.closest("#intervention-form")) {
          if (!lastSavedRecordId) {
            if (window.Swal) {
              Swal.fire("请先保存一条干预记录后再导出！", "", "info");
            } else {
              alert("请先保存一条干预记录后再导出！");
            }
            return;
          }
          // 修正：csv导出必须用 export_one 路径
          window.open(
            `/api/intervention_records/export_one?record_id=${lastSavedRecordId}&type=csv`
          );
        } else if (
          areaVisible &&
          btn.closest("#history-table-area") &&
          selectedStudent
        ) {
          // 修正：csv导出必须用 type=csv
          window.open(
            `/api/intervention_records/export?student_id=${selectedStudent.id}&type=csv`
          );
        }
      });
    });
  }

  // 返回按钮事件
  document.getElementById("btn-back")?.addEventListener("click", function () {
    document.getElementById("intervention-form").style.display = "none";
    document.getElementById("student-info-bar").classList.remove("show");
    document.getElementById("search-results").style.display = "block";
    document.getElementById("pagination-bar").style.display = "block";
    const area = document.getElementById("history-table-area");
    area.classList.remove("show");
    area.style.display = "none";
  });

  // 显示全部干预记录
  document
    .getElementById("btn-show-all")
    ?.addEventListener("click", function () {
      if (!selectedStudent || !selectedStudent.id) {
        if (window.Swal) {
          Swal.fire("请先选择学生！", "", "info");
        } else {
          alert("请先选择学生！");
        }
        return;
      }
      showHistoryTable(selectedStudent.id);
    });

  // 页面初始化
  bindExportButtons();

  // 查看全部日志（包括已删除记录）
  document
    .getElementById("btn-view-all-logs")
    ?.addEventListener("click", function () {
      if (!selectedStudent || !selectedStudent.id) {
        Swal.fire("提示", "请先选择学生", "info");
        return;
      }
      fetch(
        `/api/intervention_records/logs_all?student_id=${selectedStudent.id}`
      )
        .then((res) => res.json())
        .then((data) => {
          if (data.success && data.data.length > 0) {
            let html = data.data
              .map((log) => {
                let localTime = log.created_at
                  ? new Date(log.created_at).toLocaleString()
                  : "";
                return `<div style="border-bottom:1px solid #eee;margin-bottom:8px;padding-bottom:4px;">
              <div>记录ID：${log.record_id} 操作类型：${log.action} 操作人：${
                  log.operator || ""
                } 时间：${localTime}</div>
              <div>原始内容：<pre style="white-space:pre-wrap;">${
                log.old_content
              }</pre></div>
              <button class="btn btn-sm btn-outline-primary" onclick="restoreLog(${
                log.id
              })">恢复此版本</button>
            </div>`;
              })
              .join("");
            Swal.fire({
              title: "全部操作日志",
              html: html,
              width: 900,
              showConfirmButton: false,
            });
          } else {
            Swal.fire("无日志", "该学生暂无历史日志", "info");
          }
        });
    });

  console.log("干预记录页面加载完成");

  // 统一的URL参数处理函数
  function initializeFromParams() {
    try {
      const urlParams = new URLSearchParams(window.location.search);
      const studentId = urlParams.get("student_id");
      const autoExpand = urlParams.get("auto_expand");
      const fromComplete = urlParams.get("fromComplete") || urlParams.get("from_complete"); // 兼容两种参数名
      const showHistory = urlParams.get("show_history");

      console.log("=== 干预记录页面初始化 ===");
      console.log("URL参数:", Object.fromEntries(urlParams));

      if (studentId && autoExpand === "true") {
        console.log("✅ 开始自动加载学生信息");

        if (fromComplete === "true") {
          // 修复：正确获取学生信息，使用 'name' 而不是其他参数名
          const studentFromUrl = {
            id: parseInt(studentId),
            name: urlParams.get("name") || "", // 修复：直接使用 'name' 参数
            education_id: urlParams.get("education_id") || "",
            school: urlParams.get("school") || "",
            class_name: urlParams.get("class_name") || "",
            grade: urlParams.get("grade") || "",
            gender: urlParams.get("gender") || "",
            birthday: urlParams.get("birthday") || "",
            parent_name: urlParams.get("parent_name") || "",
          };

          console.log("✅ 从URL构建的学生信息:", studentFromUrl);
          selectedStudent = studentFromUrl;
          window.selectedStudent = selectedStudent;
          fillStudentInfoBar(selectedStudent);

          const studentInfoBar = document.getElementById("student-info-bar");
          if (studentInfoBar) {
            studentInfoBar.classList.add("show");
            studentInfoBar.style.display = "flex";
          }

          // 🔧 修复：从学生档案页面跳转时，优先显示历史记录
          if (fromComplete === "true") {
            console.log("✅ 从学生档案页面跳转，显示学生历史记录");
            showHistoryTable(studentId);
          } else if (showHistory === "true") {
            console.log("✅ 显示历史记录表格");
            showHistoryTable(studentId);
          } else {
            console.log("✅ 显示干预录入表单");
            showInterventionForm();
          }

          console.log("✅ 学生信息加载完成");
        } else {
          // 通过API加载学生信息
          loadStudentBaseInfo(studentId, () => {
            if (fromComplete === "true") {
              console.log("✅ 从学生档案页面跳转，显示学生历史记录");
              showHistoryTable(studentId);
            } else if (showHistory === "true") {
              showHistoryTable(studentId);
            } else {
              showInterventionForm();
            }
            console.log("✅ API学生信息加载完成");
          });
        }

        // 清除URL参数
        const newUrl = window.location.pathname;
        window.history.replaceState({}, document.title, newUrl);
      }
    } catch (error) {
      console.error("初始化参数处理失败:", error);
      if (window.Swal) {
        Swal.fire("错误", "页面初始化失败，请刷新重试", "error");
      }
    }
  }

  // 页面加载完成后初始化
  initializeFromParams();

  // 新增：渲染干预方式专用字段
  function renderSpecificFields(interventionType) {
    console.log("renderSpecificFields调用，干预方式:", interventionType);

    // 清空现有的专用字段
    const existingSpecificFields = document.querySelectorAll(
      ".specific-field-container"
    );
    existingSpecificFields.forEach((field) => field.remove());

    if (
      !interventionType ||
      !interventionConfig ||
      !interventionConfig.intervention_config_map
    ) {
      console.log("无配置或未选择干预方式，清空专用字段");
      return;
    }

    const typeConfig =
      interventionConfig.intervention_config_map[interventionType];
    if (!typeConfig || !typeConfig.specific_fields) {
      console.log(`未找到干预方式${interventionType}的配置`);
      return;
    }

    // 获取插入位置（在患者反应字段之前）
    const insertPosition = document.querySelector(
      'input[name="patient_reaction"]'
    );
    if (!insertPosition) {
      console.warn("未找到患者反应字段，无法插入专用字段");
      return;
    }
    const insertRow = insertPosition.closest(".row");

    // 渲染专用字段
    const specificFieldsHTML = generateSpecificFieldsHTML(
      typeConfig.specific_fields
    );
    if (specificFieldsHTML) {
      const tempDiv = document.createElement("div");
      tempDiv.innerHTML = specificFieldsHTML;

      while (tempDiv.firstChild) {
        insertRow.parentNode.insertBefore(tempDiv.firstChild, insertRow);
      }
      console.log("专用字段渲染完成");
    }
  }

  // 辅助函数：生成专用字段HTML
  function generateSpecificFieldsHTML(specificFields) {
    if (!specificFields || Object.keys(specificFields).length === 0) {
      return "";
    }

    let html = "";
    const fieldsArray = Object.entries(specificFields);

    for (let i = 0; i < fieldsArray.length; i += 4) {
      html += '<div class="row g-3 mb-4 specific-field-container">';

      for (let j = 0; j < 4 && i + j < fieldsArray.length; j++) {
        const [fieldName, fieldConfig] = fieldsArray[i + j];
        html += `<div class="col-md-3">${generateFieldHTML(
          fieldName,
          fieldConfig
        )}</div>`;
      }

      html += "</div>";
    }

    return html;
  }

  // 辅助函数：生成单个字段HTML
  function generateFieldHTML(fieldName, fieldConfig) {
    const displayName = fieldConfig.display_name || fieldName;
    let inputHTML = "";

    switch (fieldConfig.field_type) {
      case "select":
        const options = fieldConfig.options
          ? fieldConfig.options
              .map((opt) => `<option value="${opt}">${opt}</option>`)
              .join("")
          : "";
        inputHTML = `<select class="form-select" name="${fieldName}">
          <option value="">请选择</option>${options}
        </select>`;
        break;

      case "multi_checkbox":
        inputHTML = '<div class="checkbox-group">';
        if (fieldConfig.options) {
          fieldConfig.options.forEach((opt) => {
            inputHTML += `
              <div class="form-check form-check-inline">
                <input class="form-check-input" type="checkbox" 
                       name="${fieldName}" value="${opt}" id="${fieldName}_${opt}">
                <label class="form-check-label" for="${fieldName}_${opt}">${opt}</label>
              </div>
            `;
          });
        }
        inputHTML += "</div>";
        break;

      case "number_input":
        const min = fieldConfig.range ? fieldConfig.range[0] : "";
        const max = fieldConfig.range ? fieldConfig.range[1] : "";
        const unit = fieldConfig.unit || "";
        inputHTML = `<input class="form-control" type="number" name="${fieldName}" 
                           min="${min}" max="${max}" placeholder="请输入${displayName}${
          unit ? "(" + unit + ")" : ""
        }">`;
        break;

      default:
        inputHTML = `<input class="form-control" name="${fieldName}" placeholder="请输入${displayName}">`;
    }

    return `
      <label class="form-label">${displayName}</label>
      ${inputHTML}
    `;
  }

  // 修复：更新下拉框选项（增强调试）
  function updateSelectOptions() {
    if (!interventionConfig || !interventionConfig.select_options) {
      console.error(
        "配置中没有select_options数据，当前配置:",
        interventionConfig
      );
      return;
    }

    console.log(
      "开始更新下拉框选项，select_options:",
      interventionConfig.select_options
    );

    const selectMappings = {
      operation_location: 'select[name="operation_location"]',
      immediate_effect: 'select[name="immediate_effect"]',
      cooperation_level: 'select[name="cooperation_level"]',
    };

    Object.entries(selectMappings).forEach(([configKey, selector]) => {
      const selectElement = document.querySelector(selector);
      const options = interventionConfig.select_options[configKey];

      console.log(`处理字段 ${configKey}:`, {
        selector: selector,
        element: selectElement,
        options: options,
      });

      if (
        selectElement &&
        options &&
        Array.isArray(options) &&
        options.length > 0
      ) {
        selectElement.innerHTML = '<option value="">请选择</option>';
        options.forEach((option) => {
          const optionElement = document.createElement("option");
          optionElement.value = option;
          optionElement.textContent = option;
          selectElement.appendChild(optionElement);
        });
        console.log(`✅ 成功更新${configKey}选项，共${options.length}个选项`);
      } else {
        console.error(`❌ 更新${configKey}失败:`, {
          hasElement: !!selectElement,
          hasOptions: !!options,
          isArray: Array.isArray(options),
          optionsLength: options ? options.length : 0,
        });
      }
    });
  }

  // 新增：初始化干预类型下拉框
  function initializeInterventionTypeSelect() {
    if (!interventionConfig || !interventionConfig.intervention_types) {
      console.error(
        "配置中没有intervention_types数据，当前配置:",
        interventionConfig
      );
      return;
    }

    const selectElement = document.querySelector('select[name="intervention_type"]');
    const interventionTypes = interventionConfig.intervention_types;

    console.log("初始化干预类型下拉框:", {
      element: selectElement,
      types: interventionTypes,
    });

    if (selectElement && interventionTypes && Array.isArray(interventionTypes)) {
      selectElement.innerHTML = '<option value="">请选择干预方式</option>';
      interventionTypes.forEach((type) => {
        const optionElement = document.createElement("option");
        optionElement.value = type;
        optionElement.textContent = type;
        selectElement.appendChild(optionElement);
      });

      // 添加干预类型变化事件监听
      selectElement.addEventListener('change', function() {
        const selectedType = this.value;
        console.log("干预类型选择变化:", selectedType);
        if (selectedType) {
          renderSpecificFields(selectedType);
          updateCascadingOptions(selectedType);
        } else {
          renderSpecificFields(null);
        }
      });

      console.log("✅ 干预类型下拉框初始化成功");
    } else {
      console.error("❌ 干预类型下拉框初始化失败", {
        element: selectElement,
        types: interventionTypes,
      });
    }
  }

  // 新增：获取默认配置
  function getDefaultConfig() {
    return {
      intervention_types: [
        "刮痧",
        "艾灸",
        "耳穴压丸",
        "中药熏蒸",
        "热灸训练",
        "热磁脉冲",
        "拔罐",
      ],
      select_options: {
        operation_location: [
          "门诊一楼",
          "门诊二楼",
          "门诊三楼",
          "中医科",
          "眼科",
          "儿科",
        ],
        immediate_effect: ["有效", "无效", "待观察"],
        cooperation_level: ["良好", "一般", "较差"],

      },
      intervention_config_map: {},
    };
  }

  // 新增：初始化配置驱动表单
  function initializeConfigDrivenForm() {
    if (!interventionConfig) {
      console.warn("配置未加载，延迟初始化");
      return;
    }

    console.log("开始初始化配置驱动表单，配置数据:", interventionConfig);

    // 🔧 新增：渲染表头
    renderSearchResultsHeader();
    renderHistoryTableHeader();

    // 更新干预方式下拉框
    const interventionTypeSelect = document.querySelector(
      'select[name="intervention_type"]'
    );
    if (interventionTypeSelect && interventionConfig.intervention_types) {
      interventionTypeSelect.innerHTML =
        '<option value="">请选择干预方式</option>';
      interventionConfig.intervention_types.forEach((type) => {
        const option = document.createElement("option");
        option.value = type;
        option.textContent = type;
        interventionTypeSelect.appendChild(option);
      });

      // 绑定干预方式变更事件
      interventionTypeSelect.addEventListener("change", function () {
        renderSpecificFields(this.value);
        updateCascadingOptions(this.value);
      });
    }

    // 更新其他基础下拉框
    updateSelectOptions();

    // 初始化级联下拉框容器
    initializeCascadingSelects();
  }

  // 新增：初始化级联下拉框容器
  function initializeCascadingSelects() {
    console.log("🚀 开始初始化级联下拉框容器");

    // 🔧 检查Bootstrap是否正确加载
    console.log("🔧 Bootstrap检查:");
    console.log("   - window.bootstrap:", typeof window.bootstrap);
    console.log(
      "   - Bootstrap CSS类是否存在:",
      !!document.querySelector(".btn")
    );

    // 创建操作工具级联下拉框
    console.log("📝 创建操作工具级联下拉框");
    createCascadingSelect("operation_tools", "操作工具");

    // 创建消耗材料级联下拉框
    console.log("📝 创建消耗材料级联下拉框");
    createCascadingSelect("consumed_materials", "消耗材料");

    // 创建操作部位级联下拉框
    console.log("📝 创建操作部位级联下拉框");
    createCascadingSelect("operation_sites", "操作部位");

    console.log("✅ 级联下拉框容器初始化完成");

    // 🔧 最终检查：确认所有级联下拉框是否在DOM中可见
    setTimeout(() => {
      console.log("🔧 最终可见性检查:");
      let allVisible = true;
      ["operation_tools", "consumed_materials", "operation_sites"].forEach(
        (fieldName) => {
          const container = document.querySelector(`.${fieldName}-container`);
          const button = document.getElementById(`${fieldName}-dropdown`);
          if (container && button) {
            console.log(
              `   - ${fieldName}: 容器高度=${container.offsetHeight}px, 按钮高度=${button.offsetHeight}px`
            );
          } else {
            console.log(`   - ${fieldName}: ❌ 容器或按钮未找到`);
            allVisible = false;
          }
        }
      );

      // 🎯 用户友好提示
      if (allVisible) {
        const formVisible =
          document.getElementById("intervention-form").style.display !== "none";
        if (formVisible) {
          console.log("✅ 级联下拉框已成功创建并可见！");
          console.log("📍 位置：在干预录入表单的「共用字段区域」中");
          console.log("📝 包含：操作工具、消耗材料、操作部位 三个下拉框");
        } else {
          console.log("ℹ️ 级联下拉框已创建，但录入表单当前隐藏");
          console.log("💡 要查看级联下拉框，请点击学生列表中的「录入」按钮");
        }
      }
    }, 200);
  }

  // 新增：创建级联下拉框
  function createCascadingSelect(fieldName, displayName) {
    console.log(`🔍 尝试创建级联下拉框: ${fieldName}, 显示名: ${displayName}`);
    console.log(`🔍 查找容器选择器: .${fieldName}-container`);

    const container = document.querySelector(`.${fieldName}-container`);
    console.log(`🔍 找到容器:`, container);

    if (!container) {
      console.error(
        `❌ 未找到${fieldName}容器，选择器: .${fieldName}-container`
      );
      // 调试：列出所有可能的容器
      const allContainers = document.querySelectorAll('[class*="container"]');
      console.log("📋 页面中所有包含container的元素:", allContainers);
      return;
    }

    console.log(`✅ 成功找到${fieldName}容器，开始创建HTML`);

    const html = `
      <label class="form-label">${displayName}</label>
      <div class="dropdown">
        <button class="btn btn-outline-secondary dropdown-toggle w-100" type="button" 
                data-bs-toggle="dropdown" aria-expanded="false" id="${fieldName}-dropdown">
          请选择${displayName}
        </button>
        <div class="dropdown-menu w-100" id="${fieldName}-menu">
          <div class="px-3 py-2 text-muted">请先选择干预方式</div>
        </div>
      </div>
      <input type="hidden" name="${fieldName}" id="${fieldName}-hidden">
      <div class="mt-2" id="${fieldName}-selected" style="display: none;">
        <small class="text-muted">已选择：</small>
        <div id="${fieldName}-tags" class="mt-1"></div>
      </div>
    `;

    container.innerHTML = html;
    console.log(`✅ ${fieldName}级联下拉框HTML已插入到容器`);

    // 🔧 新增：检查插入后的实际DOM状态
    setTimeout(() => {
      const insertedLabel = container.querySelector(".form-label");
      const insertedButton = container.querySelector(".btn");
      const insertedDropdown = container.querySelector(".dropdown-menu");

      console.log(`🔧 ${fieldName}插入后DOM检查:`);
      console.log(`   - 容器可见性: ${getComputedStyle(container).display}`);
      console.log(`   - 容器高度: ${container.offsetHeight}px`);
      console.log(`   - 标签元素:`, insertedLabel);
      console.log(`   - 按钮元素:`, insertedButton);
      console.log(`   - 下拉菜单:`, insertedDropdown);

      if (insertedButton) {
        console.log(
          `   - 按钮可见性: ${getComputedStyle(insertedButton).display}`
        );
        console.log(`   - 按钮高度: ${insertedButton.offsetHeight}px`);
      }
    }, 100);
  }

  // 新增：更新级联选项
  function updateCascadingOptions(interventionType) {
    console.log("🔄 updateCascadingOptions 调用，干预方式:", interventionType);

    if (
      !interventionType ||
      !interventionConfig ||
      !interventionConfig.intervention_specific_options
    ) {
      // 清空级联选项
      ["operation_tools", "consumed_materials", "operation_sites"].forEach(
        (fieldName) => {
          const menu = document.getElementById(`${fieldName}-menu`);
          if (menu) {
            menu.innerHTML =
              '<div class="px-3 py-2 text-muted">请先选择干预方式</div>';
          }
        }
      );
      return;
    }

    // 🔧 修复：从intervention_specific_options获取对应干预方式的配置
    const typeConfig =
      interventionConfig.intervention_specific_options[interventionType];
    console.log("🔍 获取到的干预方式配置:", typeConfig);

    if (!typeConfig) {
      console.warn(`未找到干预方式${interventionType}的配置`);
      return;
    }

    // 更新三个级联下拉框
    ["operation_tools", "consumed_materials", "operation_sites"].forEach(
      (fieldName) => {
        const options = typeConfig[fieldName] || [];
        console.log(`🔧 更新${fieldName}，选项:`, options);
        updateCascadingMenu(fieldName, options);
      }
    );
  }

  // 新增：更新级联菜单内容
  function updateCascadingMenu(fieldName, options) {
    const menu = document.getElementById(`${fieldName}-menu`);
    const button = document.getElementById(`${fieldName}-dropdown`);

    if (!menu || !options || options.length === 0) {
      if (menu) {
        menu.innerHTML = '<div class="px-3 py-2 text-muted">暂无选项</div>';
      }
      return;
    }

    // 生成选项HTML
    let html = "";
    options.forEach((option, index) => {
      html += `
        <div class="form-check px-3 py-1">
          <input class="form-check-input" type="checkbox" 
                 id="${fieldName}_${index}" value="${option}" 
                 onchange="handleCascadingCheck('${fieldName}', this)">
          <label class="form-check-label" for="${fieldName}_${index}">
            ${option}
          </label>
        </div>
      `;
    });

    menu.innerHTML = html;
  }

  // 新增：处理级联复选框变更
  window.handleCascadingCheck = function (fieldName, checkbox) {
    const hiddenInput = document.getElementById(`${fieldName}-hidden`);
    const tagsContainer = document.getElementById(`${fieldName}-tags`);
    const selectedContainer = document.getElementById(`${fieldName}-selected`);
    const button = document.getElementById(`${fieldName}-dropdown`);

    // 收集所有选中的值
    const checkedBoxes = document.querySelectorAll(
      `input[id^="${fieldName}_"]:checked`
    );
    const selectedValues = Array.from(checkedBoxes).map((cb) => cb.value);

    // 更新隐藏字段
    hiddenInput.value = JSON.stringify(selectedValues);

    // 更新显示标签
    if (selectedValues.length > 0) {
      selectedContainer.style.display = "block";
      tagsContainer.innerHTML = selectedValues
        .map((value) => `<span class="badge bg-primary me-1">${value}</span>`)
        .join("");

      // 更新按钮文字
      button.textContent = `已选${selectedValues.length}项`;
    } else {
      selectedContainer.style.display = "none";
      button.textContent = `请选择${
        button.textContent.includes("工具")
          ? "操作工具"
          : button.textContent.includes("材料")
          ? "消耗材料"
          : "操作部位"
      }`;
    }
  };

  // 恢复干预记录日志的全局函数
  window.restoreLog = function (logId) {
    if (window.Swal) {
      Swal.fire({
        title: "确认恢复？",
        text: "恢复后将以该历史内容覆盖当前记录，是否继续？",
        icon: "warning",
        showCancelButton: true,
        confirmButtonText: "确定恢复",
        cancelButtonText: "取消",
        confirmButtonColor: "#28a745",
      }).then((result) => {
        if (result.isConfirmed) {
          fetch("/api/intervention_records/restore", {
            method: "POST",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify({ log_id: logId, operator: "用户" }),
          })
            .then((res) => res.json())
            .then((data) => {
              if (data.success) {
                let successMessage = "历史记录已成功恢复";
                let detailsHtml = "";

                // 如果后端返回了变更信息，显示详细信息
                if (data.changes && data.changes.length > 0) {
                  successMessage =
                    data.message ||
                    `恢复成功，共变更${data.changes.length}个字段`;
                  detailsHtml = `<div style="text-align:left;margin-top:10px;">
                    <strong>变更详情：</strong><br/>
                    ${data.changes.map((change) => `• ${change}`).join("<br/>")}
                  </div>`;
                }

                Swal.fire({
                  title: "恢复成功",
                  html: successMessage + detailsHtml,
                  icon: "success",
                  timer: detailsHtml ? 3000 : 1500,
                  showConfirmButton: detailsHtml ? true : false,
                });
                // 刷新历史表
                if (window.selectedStudent) {
                  showHistoryTable(window.selectedStudent.id);
                }
              } else {
                Swal.fire(
                  "恢复失败",
                  data.message || data.error || "未知错误",
                  "error"
                );
              }
            })
            .catch((err) => {
              Swal.fire("恢复失败", "网络错误：" + err.message, "error");
            });
        }
      });
    } else {
      if (confirm("确认恢复该历史记录吗？")) {
        fetch("/api/intervention_records/restore", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ log_id: logId, operator: "用户" }),
        })
          .then((res) => res.json())
          .then((data) => {
            if (data.success) {
              alert("恢复成功");
              if (window.selectedStudent) {
                showHistoryTable(window.selectedStudent.id);
              }
            } else {
              alert("恢复失败：" + (data.message || data.error || "未知错误"));
            }
          });
      }
    }
  };

  // 恢复已删除记录的全局函数
  window.restoreDeletedRecord = function (logId) {
    if (window.Swal) {
      Swal.fire({
        title: "确认恢复已删除的记录？",
        text: "将重新创建该记录，是否继续？",
        icon: "warning",
        showCancelButton: true,
        confirmButtonText: "确定恢复",
        cancelButtonText: "取消",
        confirmButtonColor: "#28a745",
      }).then((result) => {
        if (result.isConfirmed) {
          fetch("/api/intervention_records/restore_deleted", {
            method: "POST",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify({ log_id: logId, operator: "用户" }),
          })
            .then((res) => res.json())
            .then((data) => {
              if (data.success) {
                Swal.fire({
                  title: "恢复成功",
                  text: "已删除的记录已重新创建",
                  icon: "success",
                });
                // 刷新历史表
                if (window.selectedStudent) {
                  showHistoryTable(window.selectedStudent.id);
                }
              } else {
                Swal.fire(
                  "恢复失败",
                  data.message || data.error || "未知错误",
                  "error"
                );
              }
            })
            .catch((err) => {
              Swal.fire("恢复失败", "网络错误：" + err.message, "error");
            });
        }
      });
    } else {
      if (confirm("确认恢复已删除的记录吗？")) {
        fetch("/api/intervention_records/restore_deleted", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ log_id: logId, operator: "用户" }),
        })
          .then((res) => res.json())
          .then((data) => {
            if (data.success) {
              alert("恢复成功");
              if (window.selectedStudent) {
                showHistoryTable(window.selectedStudent.id);
              }
            } else {
              alert("恢复失败：" + (data.message || data.error || "未知错误"));
            }
          });
      }
    }
  };

  // 新增：安全解析数组字段的辅助函数
  function safeParseArray(value) {
    // 如果已经是数组，直接返回
    if (Array.isArray(value)) {
      return value;
    }

    // 如果是空值，返回空数组
    if (!value || value === null || value === undefined) {
      return [];
    }

    // 如果是字符串，尝试解析
    if (typeof value === "string") {
      try {
        // 处理空字符串或 "[]" 字符串
        if (value.trim() === "" || value.trim() === "[]") {
          return [];
        }
        // 尝试 JSON 解析
        const parsed = JSON.parse(value);
        return Array.isArray(parsed) ? parsed : [];
      } catch (e) {
        // 如果解析失败，假设是逗号分隔的字符串
        return value
          .split(",")
          .map((item) => item.trim())
          .filter((item) => item !== "");
      }
    }

    // 其他情况返回空数组
    return [];
  }

  // --- 学生档案按钮事件绑定 ---
  const btnStudentRecord = document.getElementById("btn-student-record");
  if (btnStudentRecord) {
    btnStudentRecord.addEventListener("click", function () {
      let studentId = null;
      // 历史表区域下，selectedStudent 可能只有 id 字段
      if (
        window.selectedStudent &&
        (window.selectedStudent.student_id || window.selectedStudent.id)
      ) {
        studentId =
          window.selectedStudent.student_id || window.selectedStudent.id;
      } else if (
        selectedStudent &&
        (selectedStudent.student_id || selectedStudent.id)
      ) {
        studentId = selectedStudent.student_id || selectedStudent.id;
      }
      if (!studentId) {
        if (window.Swal) {
          Swal.fire("无法跳转", "请先选择一名学生后再查看档案。", "warning");
        } else {
          alert("请先选择一名学生后再查看档案。");
        }
        return;
      }
      window.open(
        `/student-complete-record?student_id=${encodeURIComponent(studentId)}`,
        "_blank"
      );
    });
  }
});
